<template>
  <div v-if="isVisible" class="popover-overlay" @click.self="closePopover">
    <div class="popover-content">
      <h3 class="popover-title">AI 助手</h3>
      <div class="text-comparison">
        <div class="text-section">
          <h4>原内容</h4>
          <div class="content-box">{{ originalText }}</div>
        </div>
        <div class="divider"></div>
        <div class="text-section">
          <h4>新内容</h4>
          <div class="content-box">
            <span v-if="isLoading">正在处理中，请稍候...</span>
            <!-- 如果AI返回的是HTML或Markdown，你可能需要用v-html并确保内容安全 -->
            <!-- 为了简单起见，这里假设AI返回的是纯文本，或者CSS能处理好换行 -->
            <div v-else-if="hasError" class="error-message">{{ aiGeneratedText }}</div>
            <div v-else class="ai-content">{{ aiGeneratedText }}</div>
          </div>
        </div>
      </div>
      <div class="actions">
        <button @click="closePopover" class="button-cancel">关闭</button>
        <button @click="acceptChange" :disabled="isLoading || hasError || !aiGeneratedText" class="button-accept">
          采纳
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue';
import api from '@/api'; // 确保你的API模块路径正确

const props = defineProps({
  /* 对话框显示与否 */
  isVisible: {
    type: Boolean,
    default: false,
  },
  /* 需要润色的原始文本 */
  originalText: {
    type: String,
    required: true,
  },
});

const emit = defineEmits(['update:isVisible', 'accept', 'error']);

const aiGeneratedText = ref('');
const isLoading = ref(false);
const hasError = ref(false); // 用于标记AI处理是否出错

// 调用AI润色API
const runAiPolish = async (text) => {
  if (!text) return;

  isLoading.value = true;
  aiGeneratedText.value = ''; // 清空旧内容
  hasError.value = false; // 重置错误状态

  try {
    // 这里的 content 字段名需要与 AI 实际文本字段名（text）一致
    const res = await api.editorAi.polish({ content: text });
    if (res.code === 200) {
      aiGeneratedText.value = res.data; // res.data是润色后的文本
    } else {
      console.error("AI润色API调用失败:", res);
      aiGeneratedText.value = `润色失败：${res.message || '未知错误'}`;
      hasError.value = true;
      emit('error', `API错误：${res.message || '未知错误'}`);
    }
  } catch (error) {
    console.error("请求AI润色API时发生错误:", error);
    aiGeneratedText.value = `润色请求出错：${error.message || '网络或服务器错误'}`;
    hasError.value = true;
    emit('error', `请求错误：${error.message || '网络或服务器错误'}`);
  } finally {
    isLoading.value = false;
  }
};

// 监听isVisible和originalText的变化
// 当弹窗变为可见且有原始文本时，执行AI润色
watch(() => props.isVisible, (newVisible) => {
  if (newVisible && props.originalText) {
    runAiPolish(props.originalText);
  } else if (!newVisible) {
    // 关闭时重置状态（可选）
    aiGeneratedText.value = '';
    isLoading.value = false;
    hasError.value = false;
  }
}, { immediate: true }); // immediate: true 可以在组件初始化时，如果isVisible为true，也触发一次

// 如果原始文本在弹窗打开时发生变化，可以重新润色
// watch(() => props.originalText, (newOriginalText, oldOriginalText) => {
//   if (props.isVisible && newOriginalText && newOriginalText !== oldOriginalText) {
//     runAiPolish(newOriginalText);
//   }
// });

const closePopover = () => {
  emit('update:isVisible', false);
};

const acceptChange = () => {
  if (!isLoading.value && aiGeneratedText.value && !hasError.value) {
    emit('accept', aiGeneratedText.value);
    // 采纳后通常也会关闭悬浮框，这里由父组件控制或在此直接调用 closePopover()
  }
};
</script>

<style scoped>

.popover-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.popover-content {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 700px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.popover-title {
  margin-top: 0;
  margin-bottom: 10px;
  text-align: center;
  font-size: 1.5em;
  color: #333;
}

.text-comparison {
  display: flex;
  gap: 20px;
}

.text-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.text-section h4 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #555;
  font-size: 1em;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.content-box {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  min-height: 120px;
  overflow-y: auto;
  white-space: pre-wrap; /* 保持文本格式，如换行和空格 */
  font-size: 0.95em;
  line-height: 1.6;
}

.ai-content, .error-message {
  white-space: pre-wrap; /* 确保AI内容也能正确换行 */
}

.error-message {
  color: red;
}

.divider {
  width: 1px;
  background-color: #ddd;
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 10px;
}

.actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9em;
  transition: background-color 0.2s ease;
}

.actions button:disabled {
  background-color: #ccc;
  color: #666;
  cursor: not-allowed;
}

.button-accept {
  background-color: #4CAF50;
  color: white;
}

.button-accept:hover:not(:disabled) {
  background-color: #45a049;
}

.button-cancel {
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ccc;
}
.button-cancel:hover {
  background-color: #e0e0e0;
}
</style>
